<template>
  <template v-if="comName === BwVueComNameEnum.slot">
    <div class="bw-design-custom-slot-node"></div>
  </template>

  <template v-else-if="comName === BwVueComNameEnum.component">
    <template v-if="curEle">
      <component :is="curEle" v-bind="attrs" v-on="events" />
    </template>
    <template v-else>
      <div class="bw-design-custom-slot-node"></div>
    </template>
  </template>
</template>

<script lang="ts" setup>
import { isObject } from 'lodash-es'
import { getCustomComDesignInfo } from '@/store'
import { getInsBwUtils } from '../../../../utils/setupLogic'
import { ref, unref, markRaw, computed, watch } from 'vue'
import {
  createInsCom,
  BwVueComNameEnum,
  BwCustomComFrontTypeEnum,
  type BwGetCustomComInfoFun,
  type BwCustomComDesignInfoModel,
} from '@bitwit/base-com-render'

interface BwVueEleProps {
  is?: any
  comName?: BwVueComNameEnum
  attrs?: Record<string, any>
  events?: Record<string, any>
  frontType?: BwCustomComFrontTypeEnum
}
const props = withDefaults(defineProps<BwVueEleProps>(), {
  is: null,
  comName: BwVueComNameEnum.slot,
  frontType: BwCustomComFrontTypeEnum.pc,
})

const curEle = ref<any>(null)
const extendBwUtils = computed(() => {
  const utils = getInsBwUtils({ params: {} })
  return utils
})

/** 生成元组件实例 */
const createEle = (data: any) => {
  if (props.comName === BwVueComNameEnum.component) {
    if (typeof props.is === 'string') {
      curEle.value = props.is
    } else if (isObject(props.is)) {
      createInsCom(
        data as BwCustomComDesignInfoModel,
        props.frontType,
        getCustomComDesignInfo as BwGetCustomComInfoFun,
        unref(extendBwUtils)
      ).then((insCom: any) => {
        curEle.value = markRaw(insCom)
      })
    }
  }
}

watch(
  () => props.is,
  (newVal) => {
    createEle(newVal)
  },
  { deep: true, immediate: true }
)
</script>

<style lang="less" scoped>
.bw-design-custom-slot-node {
  width: 100%;
  height: 38px;
  background-color: #f0f0f0;
}
</style>
